package com.nsqt.biz.controller;

import com.nsqt.biz.domain.AgentDO;
import com.nsqt.biz.domain.ExcelDO;
import com.nsqt.biz.domain.WorksDO;
import com.nsqt.biz.service.AgentService;
import com.nsqt.biz.service.WorksService;
import com.nsqt.common.domain.DictDO;
import com.nsqt.common.service.DictService;
import com.nsqt.common.utils.*;
import com.nsqt.system.domain.UserDO;
import com.nsqt.system.service.UserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 作品
 */
@Controller
@RequestMapping("/biz/works")
public class WorksController {
    @Autowired
    private WorksService worksService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private UserService userService;
    @Autowired
    private DictService dictService;

    @GetMapping()
    @RequiresPermissions("biz:works:works")
    String Works() {
        return "biz/works/works";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("biz:works:works")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<WorksDO> worksList = worksService.list(query);


        int total = worksService.count(query);
        PageUtils pageUtils = new PageUtils(worksList, total);
        return pageUtils;
    }

    /**
     * 新增作品
     */
    @GetMapping("/add")
    @RequiresPermissions("biz:works:add")
    String add(Model model) {
        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        List<Long> roles = user.getRoleIds();
        Map map = new HashMap();
        map.put("limit", 200);
        map.put("offset", 0);
        if ((!roles.contains(new Long(1))) && (!roles.contains(new Long(2))) && (!roles.contains(new Long(4)))) {
            map.put("businessMan", userId);
        }
        Query query = new Query(map);
        List<AgentDO> agentList = agentService.list(query);
        model.addAttribute("agentList", agentList);

        List<UserDO> userList = userService.list(new HashMap<>());
        model.addAttribute("userList", userList);
        String approvalDate = DateUtils.date2Str(DateUtils.getDate(new Date(), 31), "YY-MM-dd");
        List<DictDO> worksTypeList = dictService.getWorkTypeList();
        model.addAttribute("worksTypeList", worksTypeList);
        model.addAttribute("businessMan", user);
        model.addAttribute("approvalDate", approvalDate);
        return "biz/works/add";
    }

    /**
     * 编辑作品
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("biz:works:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        Long userId = ShiroUtils.getUserId();
        UserDO user = userService.get(userId);
        List<Long> roles = user.getRoleIds();
        Map map = new HashMap();
        map.put("limit", 200);
        map.put("offset", 0);
        if ((!roles.contains(new Long(1))) && (!roles.contains(new Long(2))) && (!roles.contains(new Long(4)))) {
            map.put("businessMan", userId);
        }
        Query query = new Query(map);
        List<AgentDO> agentList = agentService.list(query);
        model.addAttribute("agentList", agentList);
        WorksDO works = worksService.get(id);
        if (works.getSubmitDate() == null) {
            works.setSubmitDate(DateUtils.date2Str(new Date(), "YYYY-MM-dd"));
        }
        if (works.getIsSerial() == null) {
            works.setIsSerial(0);
        }
        if (works.getWorkingDays() == null) {
            works.setWorkingDays(31);
            works.setUrgentFees("300");
            String approvalDate = DateUtils.date2Str(DateUtils.getDate(new Date(), 31), "YY-MM-dd");

            works.setApprovalDate(approvalDate);
        } else {
            int workDay = works.getWorkingDays();
            String approvalDate = DateUtils.date2Str(DateUtils.getDate(new Date(), workDay - 1), "YYYY-MM-dd");
            works.setApprovalDate(approvalDate);

        }
        if (works.getUrgentFees() == null) {
            works.setUrgentFees("300");
        }
        model.addAttribute("works", works);
        model.addAttribute("businessMan", user);

        model.addAttribute("agentList", agentList);

        List<UserDO> userList = userService.list(new HashMap<>());
        model.addAttribute("userList", userList);

        List<DictDO> worksTypeList = dictService.getWorkTypeList();
        model.addAttribute("worksTypeList", worksTypeList);
        return "biz/works/edit";
    }

    /**
     * 更改工作日
     */
    @GetMapping("/changewd/{id}")
    @RequiresPermissions("biz:works:edit")
    String changewd(@PathVariable("id") Integer id, Model model) {
        WorksDO works = worksService.get(id);
        model.addAttribute("works", works);
        return "biz/works/changewd";
    }

    /**
     * 发证
     */
    @PostMapping("/approval")
    @ResponseBody
    @RequiresPermissions("biz:works:edit")
    public R approval(Integer id) {
        if (worksService.approval(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 保存作品
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("biz:works:add")
    public R save(WorksDO works) {
        if (worksService.save(works) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改作品
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("biz:works:edit")
    public R update(WorksDO works) {
        worksService.update(works);
        return R.ok();
    }

    /**
     * 删除作品
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("biz:works:remove")
    public R remove(Integer id) {
        if (worksService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 批量删除作品
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("biz:works:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        worksService.batchRemove(ids);
        return R.ok();
    }

    /*
     * 导入excel文件
     * @return
     */
    @ResponseBody
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map resultMap = new HashMap();
        if (file != null) {
            int number = saveFile(resultMap, file);
            if (resultMap.get("code").equals("0")) {
                Map fileMap = new HashMap();
                fileMap.put("src", "");
                resultMap.put("data", fileMap);

                return R.ok(number + "条记录被成功导入。");
            } else {
                return R.error();
            }
        }
        return R.error();
    }

    /**
     * 保存导入的Excel数据到数据库里
     *
     * @param resultMap
     * @param file
     */
    public int saveFile(Map<String, Object> resultMap, MultipartFile file) {
        if (file.isEmpty()) {
            return 0;
        }
        int number = 0;
        Long userId = ShiroUtils.getUserId();
        try {
            List<Object[]> objects = ExcelUtils.importExcel(file.getInputStream());

            for (Object[] os : objects) {
                WorksDO works = new WorksDO();
                works.setStatus(0);
                works.setBusinessMan(Integer.parseInt(userId.toString()));
                if (os.length > 1) {
                    works.setSn(String.valueOf(os[0]));
                    works.setCopyrightOwner(String.valueOf(os[1]));
                    works.setWorksName(String.valueOf(os[2]));
                    works.setAgentCompany(String.valueOf(os[3]));
                    works.setWorkingDays(StringUtils.getIntValue(String.valueOf(os[4])));
                    works.setBusinessMan(userId.intValue());
                } else {
                    String whole = (String.valueOf(os[0]));
                    String[] strs = whole.split(" ");
                    works.setSn(strs[0]);
                    works.setCopyrightOwner(strs[1]);
                    works.setWorksName(strs[2]);
                }
                if (worksService.getBySn(works.getSn()) == null) {
                    worksService.save(works);
                    number++;
                } else {
                    worksService.update(works);
                }
            }

            resultMap.put("filename", file.getOriginalFilename());
            resultMap.put("saveUrl", "");
            resultMap.put("code", "0");
            resultMap.put("msg", number + "条记录导入成功！");
            return number;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", "-2");
            resultMap.put("msg", "导入异常！");
            return 0;
        }
    }

    /**
     * 导出到excel
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/excel")
    @RequiresPermissions("biz:software:software")
    public void exports(HttpServletRequest request, HttpServletResponse response) {
        int rowIndex = 0;

        ExcelDO data = new ExcelDO();
        data.setName("exports");
        List<String> titles = new ArrayList();
        titles.add("提交日期");    //1
        titles.add("流水号");    //2
        titles.add("著作权人");    //3
        titles.add("作品名称");    //4
        titles.add("工作日");    //5
        titles.add("出证日");    //3
        titles.add("官费");    //4
        titles.add("代理商");    //5
        titles.add("快递");    //5
        data.setTitles(titles);

        //查询列表数据

        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String agent = request.getParameter("agentCompany");


        if (startDate == null || startDate.equals("")) {
            startDate = DateUtils.getLastMonthFirstDay();
        }
        if (endDate == null || endDate.equals("")) {
            endDate = DateUtils.getLastMonthLastDay();
        }
        Map map = new HashMap();
        map.put("limit", 10);
        map.put("offset", 20);
        Query query = new Query(map);
        query.put("startDate", startDate);
        query.put("endDate", endDate);
        query.put("agentCompany", agent);

        List<WorksDO> worksList = worksService.listExcel(query);
        List<List<Object>> rows = new ArrayList();
        for (int i = 0, length = worksList.size(); i < length; i++) {
            String businessType = "";
            String type = "";
            String businessMan = "";
            String agentCompany = "";
            WorksDO works = worksList.get(i);
            List<Object> row = new ArrayList();
            row.add(works.getSubmitDate());
            row.add(works.getSn());
            row.add(works.getCopyrightOwner());
            row.add(works.getWorksName());
            row.add(works.getWorkingDays());
            row.add(works.getApprovalDate());
            row.add(works.getOfficialFees());
            row.add(works.getAgentCompany());
            if (works.getStatus() == 4) {
                row.add("是");
            } else {
                row.add("否");
            }
            rows.add(row);
        }
        data.setRows(rows);
        try {
            String fileName = startDate + "to" + endDate;
            ExcelUtils.exportExcel(response, fileName, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
